// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const taskInput = document.getElementById('taskInput');
    const addTaskBtn = document.getElementById('addTaskBtn');
    const taskList = document.getElementById('taskList');
    const tasksCount = document.getElementById('tasksCount');
    const clearCompletedBtn = document.getElementById('clearCompletedBtn');
    const filterBtns = document.querySelectorAll('.filter-btn');
    
    // 当前过滤状态
    let currentFilter = 'all';
    
    // 从本地存储加载任务
    let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
    
    // 初始化应用
    function init() {
        renderTasks();
        updateTasksCount();
        
        // 添加事件监听器
        addTaskBtn.addEventListener('click', addTask);
        taskInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                addTask();
            }
        });
        
        clearCompletedBtn.addEventListener('click', clearCompletedTasks);
        
        filterBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // 更新活动按钮状态
                filterBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                // 更新过滤状态并重新渲染
                currentFilter = this.dataset.filter;
                renderTasks();
            });
        });
    }
    
    // 添加新任务
    function addTask() {
        const taskText = taskInput.value.trim();
        
        if (taskText === '') {
            alert('请输入任务内容');
            return;
        }
        
        // 创建新任务对象
        const newTask = {
            id: Date.now(),
            text: taskText,
            completed: false,
            createdAt: new Date()
        };
        
        // 添加到任务数组
        tasks.push(newTask);
        
        // 保存到本地存储
        saveTasks();
        
        // 清空输入框
        taskInput.value = '';
        
        // 重新渲染任务列表
        renderTasks();
        updateTasksCount();
    }
    
    // 渲染任务列表
    function renderTasks() {
        // 清空当前列表
        taskList.innerHTML = '';
        
        // 根据过滤状态获取任务
        let filteredTasks = tasks;
        if (currentFilter === 'active') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (currentFilter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 渲染每个任务
        filteredTasks.forEach(task => {
            const taskItem = document.createElement('li');
            taskItem.className = `task-item ${task.completed ? 'completed' : ''}`;
            taskItem.dataset.id = task.id;
            
            taskItem.innerHTML = `
                <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
                <span class="task-text">${task.text}</span>
                <button class="delete-btn">×</button>
            `;
            
            taskList.appendChild(taskItem);
        });
        
        // 添加任务项事件监听器
        document.querySelectorAll('.task-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', toggleTaskCompleted);
        });
        
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', deleteTask);
        });
    }
    
    // 切换任务完成状态
    function toggleTaskCompleted(e) {
        const taskId = parseInt(e.target.closest('.task-item').dataset.id);
        const task = tasks.find(task => task.id === taskId);
        
        if (task) {
            task.completed = e.target.checked;
            saveTasks();
            renderTasks();
            updateTasksCount();
        }
    }
    
    // 删除任务
    function deleteTask(e) {
        const taskId = parseInt(e.target.closest('.task-item').dataset.id);
        tasks = tasks.filter(task => task.id !== taskId);
        
        saveTasks();
        renderTasks();
        updateTasksCount();
    }
    
    // 清除已完成任务
    function clearCompletedTasks() {
        tasks = tasks.filter(task => !task.completed);
        saveTasks();
        renderTasks();
        updateTasksCount();
    }
    
    // 更新任务计数
    function updateTasksCount() {
        const totalTasks = tasks.length;
        const completedTasks = tasks.filter(task => task.completed).length;
        const activeTasks = totalTasks - completedTasks;
        
        tasksCount.textContent = `${activeTasks} 个待完成任务，${completedTasks} 个已完成`;
    }
    
    // 保存任务到本地存储
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 初始化应用
    init();
});